<!-- 
    上面显示容器 下面图片排列
    file-list / v-model:file-list : 默认显示图片
    list-type ：文件列表类型
 -->
<template>
    <el-upload  ref="upload"  class="upload-content" action="#" v-model:file-list="fileList" :show-file-list="false" list-type="picture" multiple 
    :drag="drag"
    :limit="limit"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :http-request="submitUpload"
    :class="{ 'hide-upload': hideUpload }" >
        <template v-if="displayType == '0'"></template>
        <template v-else-if="displayType == '1'">
            <div class="displayArea1">  <!-- 引用组件时 父组件显示区域 可根据不同样式 自定义修改  -->
                <el-icon size="30"><UploadFilled /></el-icon><span> 点击/将文件拖到此处，自动上传</span>
            </div>
        </template>
        <template v-else-if="displayType == '2'">
            <div class="displayArea2">  <!-- 引用组件时 父组件显示区域 可根据不同样式 自定义修改  -->
                <el-icon size="40"><UploadFilled /></el-icon>
                <p> 点击/将文件拖到此处，自动上传</p>
            </div>
        </template>
        <template v-else-if="displayType == '3'">
            <div class="displayArea3">  <!-- 引用组件时 父组件显示区域 可根据不同样式 自定义修改  -->
                <el-icon size="40"><UploadFilled /></el-icon>
                <p> 点击/将文件拖到此处，自动上传</p>
            </div>
        </template>
        <template v-else>
            <div class="displayArea">  <!-- 引用组件时 父组件显示区域 可根据不同样式 自定义修改  -->
                <el-icon size="30"><UploadFilled /></el-icon><span> 点击/将文件拖到此处，自动上传</span>
            </div>
        </template>

        <template #tip v-if="displayType != '0'">
            <div v-if="props.type=='xls/xlsx'" class="tips" style="font-size: 12px;">
                <el-icon><Warning color="#2158F3"/></el-icon>请上传XLS/XLSX文件，大小在{{props.fileSize}}M以内，最多{{props.limit}}个
            </div>
            <div v-if="props.type=='jpg/png/jpeg'" class="tips" style="font-size: 12px;">
                <el-icon><Warning color="#2158F3"/></el-icon>请上传JPG/PNG文件，大小在{{props.fileSize}}M以内，最多{{props.limit}}个
            </div>
            <div v-if="props.type=='jpg/png/jpeg/pdf'" class="tips" style="font-size: 12px;">
                <el-icon><Warning color="#2158F3"/></el-icon>请上传JPG/PNG/PDF文件，大小在{{props.fileSize}}M以内，最多{{props.limit}}个
            </div> 
            <div v-if="props.type=='jpg/png/jpeg/pdf/zip'" class="tips" style="font-size: 12px;">
                <el-icon><Warning color="#2158F3"/></el-icon>请上传JPG/PNG/PDF/ZIP文件，大小在{{props.fileSize}}M以内，最多{{props.limit}}个
            </div> 
            <div v-if="props.type=='pdf/doc/docx/xls/xlsx/jpg/jpeg/png/zip'" style="font-size: 12px;">
                <el-icon><Warning color="#2158F3"/></el-icon>请上传PDF/DOC/DOCX/XLS/XLSX/JPG/JPEG/PNG/ZIP文件，大小在{{props.fileSize}}M以内，最多{{props.limit}}个
            </div>
            <div v-if="props.type=='jpg/jpeg/png/zip/pdf/doc/docx'" style="font-size: 12px;">
                <el-icon><Warning color="#2158F3"/></el-icon>请上传PDF/DOC/DOCX/JPG/JPEG/PNG/ZIP文件，大小在{{props.fileSize}}M以内，最多{{props.limit}}个
            </div>
        </template>
    </el-upload>
    <!-- 自定义显示区域 -->
    <template v-if="fileList.length">
        <el-row gutter="10" class="marginTop10" style="width: 100%">
            <el-col :span="showNum" v-for="(file, index) in fileList" :key="index" class="custom-file-item">
                <div style="width: 100%;">
                    <template v-if="file.fileContentType =='application/octet-stream'">
                        <img src="@/assets/images/octet.png" alt="预览图" style="width: 100%;height:100px;border-radius: 5px;" />
                    </template>
                    <template v-else-if="file.fileContentType =='application/pdf'">
                        <img src="@/assets/images/pdf.png" alt="预览图" style="width: 100%;height:100px;border-radius: 5px;" />
                    </template>
                    <template v-else-if="file.fileContentType =='application/vnd.openxmlformats-officedocument.wordprocessingml.document'">
                        <img src="@/assets/images/word.png" alt="预览图" style="width: 100%;height:100px;border-radius: 5px;" />
                    </template>
                    <template v-else-if="file.fileContentType =='application/msword'">
                        <img src="@/assets/images/word.png" alt="预览图" style="width: 100%;height:100px;border-radius: 5px;" />
                    </template>
                    <template v-else-if="file.fileContentType =='application/x-zip-compressed'">
                        <img src="@/assets/images/zip.png" alt="预览图" style="width: 100%;height:100px;border-radius: 5px;" />
                    </template>
                    <template v-else-if="file.fileContentType =='image/jpeg' || file.fileContentType =='image/png' || file.fileContentType =='image/jpg'" >
                        <img :src="file.url" alt="预览图" style="width: 100%;height: 100px;border-radius: 5px;" />
                    </template>
                    <el-row class="maskLayer" justify="center">
                        <!-- 查看 -->
                        <el-col :span="6" class="zoom-in" v-if="file.fileContentType =='application/pdf' || file.fileContentType =='application/octet-stream'">
                            <el-icon size="20" @click="showPdf(file)"><zoom-in  color="#00ff00"/></el-icon>
                        </el-col>
                        <el-col :span="6" v-if="file.fileContentType =='image/jpeg' || file.fileContentType =='image/png' || file.fileContentType =='image/jpg'" class="zoom-in" >
                            <el-icon size="20" @click="handlePictureCardPreview(file)"><zoom-in  color="#00ff00"/></el-icon>
                        </el-col>
                        <!-- 下载 -->
                        <el-col :span="6" class="download" v-if="displayType == '0' || displayType == '3'">
                            <el-icon size="20"><Download color="#00ff00" @click="basicTools.downloadFile(file)"/></el-icon>
                        </el-col>
                        <!-- 删除 -->
                        <el-col :span="6" class="delete" v-if="displayType != '0'">
                            <el-icon size="20"  @click="handleRemove(file)"><Delete color="#ff0000"/></el-icon>
                        </el-col>
                    </el-row>
                </div>
            </el-col>
        </el-row>
    </template>
    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;" />
    </el-dialog>
</template>
   
<script lang="ts" setup>
    import { ref,onMounted, computed, watch,watchEffect  } from 'vue';
    import { uploadFile } from '@/api/system/upload'   //上传 附件 （EXCEL,WORD,PDF,ZIP,RAR,JPG,PNG...）
    import { recordsUpload } from '@/api/boxManage/BoxRecords'  //购箱记录导入接口
    import { ElMessage } from 'element-plus';
    import { uploadBox } from '@/api/boxManage/index' // 集装箱导入接口（EXCEL格式导入）功能接口
    import { uploadYard } from '@/api/boxManage/yard' // 堆场导入接口（EXCEL格式导入）功能接口
    import { compressAccurately } from 'image-conversion' // 图片压缩工具
    import basicTools from '@/tools/index'
    const emit = defineEmits(['updateInfo','uploadSuccess','excelUploadError'])

    const upload = ref()
    const props = defineProps({
        urlList: {
            type: Array,
            default: () => {
                return []
            }
        },
        fileSize: { // 上传文件大小 单位M
            type: Number,
            default: 3
        },
        limit: { // 最大上传文件数
            type: Number,
            default: 1
        },
        type:{ //可上传附件类型
            type: String,
            default: 'jpg'
        },
        styleType:  { // 显示区域的显示
            type: String,
            default: 'default' // default- 默认样式  card- 卡片样式
        },
        drag: {  // 是否可拖拽上传   
            type: Boolean,
            default: false
        },
        displayType:{ // 自定义不同样式类型
            type: String,
            default: 'default'
        },
        showNumber: {   // 每行可显示图片数量
            type: String,
            default: '6' 
        },
        purpose:{  //  import：导入功能（一般用于：导入集装箱 导入堆场---）  upload:上传功能（一般用于：上传附件等）
            type: String,  
            default: 'upload'
        },
        use: {  //  container: 一般此属性配合purpose 属性使用（指 具体功能点 container：集装箱导入功能）  
            type: String,  
            default: 'container'
        },
        clearFile:{ // 是否需要清空 上传记录
            type: Boolean,
            default: false
        },
        hideUpload: { // 是否显示上传按钮
            type: Boolean,
            default: false
        }

    })
   
    const showNum = computed(() => {
        const num = Number(props.showNumber);
        return num ? 24 / num : 24; // 防止除以 0 或无效值
    });
    const fileList = ref([])
    const compressedFile = ref();//压缩后的文件信息
    // 文件上传前
    const beforeUpload = (file) => {
        const typeList = props.type.split("/").map(item => {
            if(item == 'pdf'){
                return 'application/pdf'
            }else if(item == 'xls'){
                return 'application/vnd.ms-excel'
            }else if(item == 'xlsx'){
                return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            }else if(item == 'doc'){
                return 'application/msword'
            }else if(item == 'docx'){
                return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            }else if(item == 'zip'){
                return 'application/x-zip-compressed'
            }else{
                return  `image/${item}`
            }
        })
        const flieM = file.size / 1024 / 1024 //字节转为M
        if(flieM > props.fileSize){
            if(file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/jpg'){
                compressedFile.value = null
                ElMessage.warning("部分图片体积过大，系统会对体积过大图片进行压缩，如何显示效果不满意，可重新上传合规图片")
                compressAccurately(file,props.fileSize).then(blob => {
                    console.log("file",file)
                    compressedFile.value = new File([blob], file.name, {
                        type: blob.type,
                        lastModified: file.lastModified
                    });
                    compressedFile.value.uid = file.uid
                })
            }else{
                ElMessage.warning("文件大小不能超过" + props.fileSize + "M")
                return false
            }
            
            
        }else if(!typeList.includes(file.type)){ 
            ElMessage.warning("此文件格式禁止上传")
            return false;
        }
        return true; // 返回 true 表示通过校验，继续上传
        // else{
        //     submitUpload(file)
        // }
    }

    //上传文件
    const submitUpload = async (value) => {
        const formData = new FormData();
        if(compressedFile.value){
            formData.append('file', compressedFile.value);
        }else{
            formData.append('file', value.file);
        }
        try {
            if(props.purpose == 'import'){  // 导入功能
                switch (props.use) {
                    case 'container':
                        await uploadBox(formData).then((res: any) => {
                            if(res.code  == "00000"){
                                emit('uploadSuccess',res)
                            }else{
                                emit('excelUploadError',res)
                            }
                        })
                        break;
                    case 'yard':
                        await uploadYard(formData).then((res: any) => {
                            if(res.code  == "00000"){
                                emit('uploadSuccess',res)
                            }else{
                                emit('excelUploadError',res)
                            }
                        })
                        break;
                    case 'record':
                        await recordsUpload(formData).then((res: any) => {
                            if(res.code  == "00000"){
                                emit('uploadSuccess',res)
                            }else{
                                emit('excelUploadError',res)
                            }
                        })
                        break;
                    default:
                        console.log(props.purpose,props.use)
                        break;
                    
                }
            }else if(props.purpose == 'upload'){  //上传功能
                await uploadFile(formData).then((res) =>{
                    fileList.value.push(res.data); // 更新文件列表
                    fileList.value = fileList.value.filter((file) => !file.url.startsWith('blob:'));
                    emit('updateInfo',fileList.value)
                    value.onSuccess(res); // 通知组件上传成功
                    compressedFile.value = null;
                });

                // if(props.displayType == '1'){
                //     upload.value!.clearFiles()
                //     recordsUpload(formData).then(res => {
                //         emit('updateInfo',res)
                //     })
                // }else{
                    
                // }
            }else{
                    console.log('purpose',props.purpose)
            }
           
            
        } catch (err) {
            value.onError(err); // 通知组件上传失败
        }
    }
    // 文件超出限制时
    const handleExceed = (files, fileList) => {
        ElMessage.warning(`最多添加${props.limit}个附件`)

    }
   
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const handlePictureCardPreview = (file) => {
        dialogImageUrl.value = file.url!
        dialogVisible.value = true
    }
    const showPdf = (file)=>{
        // console.log('123123123',file)
        window.open(file.url, '_blank');
    }
    const handleRemove = (file) => {
        const newFile =  fileList.value.filter(item => item.uid != file.uid)
        emit('updateInfo',newFile)
        fileList.value = newFile
    }
    const downloadImage = (file) => {
        basicTools.downloadImage(file)
        // const link = document.createElement("a");
        // link.href = file.url;
        // link.download = file.originalFileName;
        // link.style.display = 'none';
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
    }

    // function downloadFile(url, filename) {
    //     const a = document.createElement('a');
    //     a.href = url;
    //     a.download = filename || 'download'; // 指定下载的文件名
    //     document.body.appendChild(a);
    //     a.click();
    //     document.body.removeChild(a);
    // }


    watchEffect(() => {
      fileList.value = props.urlList
    })
    onMounted(()=>{
        try{
            fileList.value = JSON.parse(props.urlList)
        }catch(err){
        }  
        
    })
   
    const clearFiles = () => {
        fileList.value = []
    }
    defineExpose({
      fileList,
      clearFiles
    })
</script>
<style lang="scss" scoped>
.upload-content{
    width: 100%;
    :deep(.el-upload){
        width: 100%;
    }
}
  .displayArea{
    width: 800px;
    height: 60px;
    background-color: #f1f1f1;
    border:1px dashed #ccc;
    border-radius: 3px;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;    /* 垂直居中 */
  }

    
  //修改图片列表样式
  .custom-file-item{
    position: relative;
  }
  .maskLayer{
    display: block;
    position:absolute;
    left: 0;
    top: 0;
    width: 0;
    width: 100%;
    height: 100px;
    background-color: #000;
    opacity: 0;
    border-radius: 5px;
    text-align: center;
    &:hover {
        opacity: 0.5;
        cursor: pointer;
    }
    .zoom-in{
        margin-top: 22%;
        width: 30%;
        display: inline-block;
       
    }
    .download{
        margin-top: 22%;
        width: 30%;
        display: inline-block;
       
    }
    .delete{
        margin-top: 22%;
        width: 30%;
        display: inline-block;
    }
  }
  .tips{
    font-size: 12px;
    text-align: center;
  }

  .displayArea1{
    width: 100%;
    height: 150px;
    background-color: #f1f1f1;
    border-radius: 3px;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;    /* 垂直居中 */
  }
  .displayArea2{
    width: 100%;
    height: 150px;
    padding-top: 30px;
    background-color: #f1f1f1;
    border-radius: 3px;
    text-align: center;
  }
  .displayArea3{
    width: 100%;
    height: 60px;
    background-color: #f1f1f1;
    border-radius: 3px;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;    /* 垂直居中 */
  }
  
  :deep(.el-upload-dragger){
    padding: 0 !important;
  }
  /* 使用 /deep/ 或 ::v-deep 进行样式穿透 */
  .hide-upload{
        display: none !important;
   }
</style>